package com.xuhuan.demo.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author huan.xu
 * @Date 2022/11/15 15:06
 * @Description zip工具类
 */
@Slf4j
public class ZipUtil {

    private ZipUtil() {
    }

    /**
     * 压缩文件
     * @param inputFileName 需要压缩的文件夹或者文件名称
     * @param zipFileName 压缩后的文件名称
     * @return
     */
    public static Boolean zip(String inputFileName, String zipFileName) {
        try {
            zip(zipFileName, new File(inputFileName));
            return true;
        } catch (Exception e) {
            log.error("压缩文件失败：{}", e);
        }
        return false;
    }

    /**
     * 压缩文件
     * @param zipFileName
     * @param inputFile
     * @throws Exception
     */
    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, "");
        out.flush();
        out.close();
    }

    /**
     * 压缩文件
     * @param zipOutputStream
     * @param file
     * @param base
     * @throws Exception
     */
    private static void zip(ZipOutputStream zipOutputStream, File file, String base)
        throws Exception {
        if (file.isDirectory()) {
            File[] fl = file.listFiles();
            zipOutputStream.putNextEntry(new ZipEntry(base + File.separator));
            base = base.length() == 0 ? "" : base + File.separator;
            for (int i = 0; i < fl.length; i++) {
                zip(zipOutputStream, fl[i], base + fl[i].getName());
            }
        } else {
            zipOutputStream.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(file);
            int b;
            while ((b = in.read()) != -1) {
                zipOutputStream.write(b);
            }
            in.close();
        }
    }

    public static void main(String[] args) {
        String needZipPath = "C:\\Users\\Administrator\\Desktop\\filedir";
        String zipFilePath = "C:\\Users\\Administrator\\Desktop\\filedir-zip.zip";
        log.info("开始压缩文件，218M");
        long smallStartTime = System.currentTimeMillis();
        Boolean zip = zip(needZipPath, zipFilePath);
        long smallEndTime = System.currentTimeMillis();
        log.info("压缩文件完成，时间[{}]秒",(smallEndTime-smallStartTime)/1000);

    }
}
